import express = require('express');
import {Promise} from 'es6-promise';
import {Request,Response} from "express";

import {MongoColls} from "../../config/mongo";
import PWSApp from "../../core/app";
import HomeBaseAction from "./act.base";
import {RouteType} from "../../core/defines";
import {ErrCode} from "../../core/error.code";
import RegionModel from "../../models/mod.region";

export default class Region extends HomeBaseAction {
    private _regionModel: RegionModel;

    constructor(app: PWSApp) {
        super(app);
        this._regionModel = new RegionModel(this.db.collection(MongoColls.OTHER_PRC_REGION));
    }

    name() { return `${this.app.name}Region`; }

    protected _setRoutes() {
        this._route(RouteType.GET, '/region', this._actGetProvinces);
        this._route(RouteType.GET, '/region/prov', this._actRegionById);
    }

    protected _actGetProvinces(req: Request, res: Response){
        this._regionModel.getAllProvinces().then((data) => {
            res.send({
                provinces: data,
                err_code: ErrCode.Success
            });
        })
    }

    private _actRegionById(req: Request, res: Response) {
        let{cid, pid} = req.query;
        Promise.resolve().then(() => {
            if(!cid && !pid){
                return Promise.reject({err_code: ErrCode.ArgsMissing});
            }
            if(cid){
                return this._regionModel.getDistrictsByCityId(parseInt(cid));
            }
            if(pid){
                return this._regionModel.getCitiesByProvinceId(parseInt(pid));
            }
        }).then((data) => {
            res.send({data, err_code: ErrCode.Success});
        }).catch((err: any) => {
            this._errHandler(req, res, err);
        });
    }
}